import React, { useEffect, useState } from "react";
import { modalPropsType, roleTypes } from "@/constants/types";
import { Modal, Form, Input, Radio, Cascader, Select } from "antd";
import { isEmptyObj } from "@/utils/util";
import { yesOrNo, disabledStatus } from "@/constants/dictData";
// import { PlusOutlined, MinusOutlined } from "@ant-design/icons";
import { useComponentDidMount } from "@/hooks";
import { fetchInnerUserDetail, fetchRoleListOptions } from "../../services";

const {Item} = Form;
const rules = [{required: true, message: '此项必填'}];
const labelCol = {span: 6};
const initValues = {status: 0}

const UserUpdateModal = ({visible, onCancel, onSubmit, currentRow, loading, title, treeData, selectNode}: modalPropsType) => {
  const [form] = Form.useForm();
  const [roles, setRoles] = useState<roleTypes []>([]);

  const search = async (id: string) => {
    const res = await fetchInnerUserDetail({id});
    form.setFieldsValue({
      ...(res || {}),
      deptId: res?.deptIds?.length ? res?.deptIds : []
    });
  }

  const setDeptToForm = () => {
    let arr: any [] = [];
    const searchTree = (nodeList: any [], nodes: any []) => {
      nodeList.forEach((element: any) => {
        if (element.id === selectNode.id) {
          arr = [...nodes, element.id];
        } else if (element?.children?.length > 0) {
          searchTree(element.children, [...nodes, element.id]);
        }
      });
    }
    searchTree(treeData, []);
    form.setFieldValue('deptId', arr);
  }

  const handleSubmit = async () => {
    const res = await form.validateFields();
    onSubmit({
      ...res,
      id: currentRow?.id,
      deptId: res?.deptId?.[res?.deptId?.length - 1],
      roleName: roles?.filter(v => res?.roleIds?.includes(v?.value))?.map(v => v?.label).join(',')
    });
  }

  useEffect(() => {
    if (!isEmptyObj(currentRow)) {
      search(currentRow?.id);
    } else {
      form.resetFields();
    }
  }, [JSON.stringify(currentRow)]);

  useComponentDidMount(() => {
    fetchRoleListOptions().then(res => {
      setRoles((res || []).map((v: any) => ({label: v?.roleName, value: v?.id})));
    });
    setDeptToForm();
  })

  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      maskClosable={false}
      width="600px"
    >
      <Form form={form} initialValues={initValues} labelCol={labelCol} style={{marginTop: 20, marginBottom: 20}}>
        <Item label="所属公司" rules={rules}>
          <Input disabled value={treeData?.[0]?.name || ''} />
        </Item>
        {/* <Form.List name="roleIds">
          {(fields) =>
            fields.map((field, fieldIndex) => (
              <Row gutter={20} key={field.name}>
                <Col span={12}>
                  <Form.Item name={[field.name, 'dept']} label="部门" labelCol={{span: 8}}>
                    <Cascader 
                      options={treeData}
                      fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                      style={{width: 150}} />
                  </Form.Item>
                </Col>  
                <Col span={9}>
                  <Form.Item name={[field.name, 'isLeader']} label="是否负责人" labelCol={{span: 10}}>
                    <Radio.Group>
                      <Space direction="horizontal">
                        {
                          yesOrNo?.map(v => (
                            <Radio key={v.value} value={v.value}>{v.label}</Radio>
                          ))
                        }
                      </Space>
                    </Radio.Group>
                  </Form.Item>
                </Col>
                <Col span={3}>
                  {fieldIndex === 0 && <Button type="primary" icon={<PlusOutlined />} />}
                  {fieldIndex > 0 && <Button type="primary" icon={<MinusOutlined />} />}
                </Col>
              </Row>
            ))
          }
        </Form.List> */}
        <Item name='deptId' label="部门" rules={rules}>
          <Cascader 
            options={treeData}
            changeOnSelect
            fieldNames={{ label: 'name', value: 'id', children: 'children' }}
            />
        </Item>
        <Item name='isLeader' label="是否部门负责人" rules={rules}>
          <Radio.Group options={yesOrNo}  />
        </Item>
        <Item name="userName" label="登录账户" rules={rules}>
          <Input disabled={!!currentRow} />
        </Item>
        <Item name="realName" label="员工姓名" rules={rules}>
          <Input />
        </Item>
        <Item name="mobile" label="手机号" rules={rules}>
          <Input maxLength={11} />
        </Item>
        <Item name="roleIds" label="角色" rules={rules}>
          <Select mode="multiple" options={roles} />
        </Item>
        <Item name="status" label="状态" rules={rules}>
          <Radio.Group options={disabledStatus}  />
        </Item>
      </Form>
    </Modal>
  );
}
export default UserUpdateModal;